export default class AdCustomRuleBuilder {
  private data: Record<string, string> = {};

  // 设置用户ID（建议脱敏）
  setUserId(userId: string): this {
    this.data['user_id'] = userId;
    return this;
  }

  // 是否新用户
  setIsNewUser(isNew: boolean): this {
    this.data['is_new_user'] = isNew ? '1' : '0';
    return this;
  }

  // 设置兴趣
  setInterest(tag: string): this {
    this.data['interest'] = tag;
    return this;
  }

  // 连续登录天数
  setLoginDays(days: number): this {
    this.data['login_days'] = days.toString();
    return this;
  }

  // 累计登录天数
  setLoginTotalDays(days: number): this {
    this.data['login_total_days'] = days.toString();
    return this;
  }

  // 游戏关卡
  setLevel(level: number): this {
    this.data['level'] = level.toString();
    return this;
  }

  // 激励类型（如 revive_card / double_gold）
  setRewardType(type: string): this {
    this.data['reward_type'] = type;
    return this;
  }

  // 当前广告场景（如 login / fail / pass）
  setAdScene(scene: string): this {
    this.data['ad_scene'] = scene;
    return this;
  }

  // 是否为付费用户
  setIsPayingUser(isPaying: boolean): this {
    this.data['is_paying_user'] = isPaying ? '1' : '0';
    return this;
  }

  // 设置任意自定义字段（扩展）
  setCustomField(key: string, value: string | number | boolean): this {
    this.data[key] = String(value);
    return this;
  }

  // 获取最终 JSON 对象
  build(): Record<string, string> {
    return this.data;
  }

  // 获取 JSON 字符串（适合 SDK 上传）
  buildString(): string {
    return JSON.stringify(this.data);
  }

  // 静态方法：一次性生成 custom_rule 字段
  static create(config: {
    user_id?: string;
    is_new_user?: boolean;
    interest?: string;
    login_days?: number;
    level?: number;
    reward_type?: string;
    ad_scene?: string;
    is_paying_user?: boolean;
    [key: string]: any;
  }): Record<string, string> {
    const builder = new AdCustomRuleBuilder();
    if (config.user_id) builder.setUserId(config.user_id);
    if (typeof config.is_new_user === 'boolean') builder.setIsNewUser(config.is_new_user);
    if (config.interest) builder.setInterest(config.interest);
    if (typeof config.login_days === 'number') builder.setLoginDays(config.login_days);
    if (typeof config.level === 'number') builder.setLevel(config.level);
    if (config.reward_type) builder.setRewardType(config.reward_type);
    if (config.ad_scene) builder.setAdScene(config.ad_scene);
    if (typeof config.is_paying_user === 'boolean') builder.setIsPayingUser(config.is_paying_user);

    // 其他字段动态扩展
    for (const key in config) {
      if (!(key in builder.data)) {
        builder.setCustomField(key, config[key]);
      }
    }

    return builder.build();
  }
}
